package org.lucky_common.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

public class MD5Utils {

    /**
     * @Description: MD5加密
     * @Auther: ONESTAR
     * @Date: 17:19 2022/12/23
     * @Param: 要加密的字符串
     * @Return: 加密后的字符串
     */
    public static String code(String str) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(str.getBytes());
            byte[] byteDigest = md.digest();
            int i;
            StringBuffer buf = new StringBuffer("");
            for (int offset = 0; offset < byteDigest.length; offset++) {
                i = byteDigest[offset];
                if (i < 0)
                    i += 256;
                if (i < 16)
                    buf.append("0");
                buf.append(Integer.toHexString(i));
            }
            //32位加密
//            return buf.toString();
            // 16位的加密
//            return buf.toString().substring(8, 24);
            //自定义位数的加密
            return buf.toString().substring(8, 14);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return "加密出错";
        }
    }

    /**
     * 加密
     * @param context
     */
    public static String encrypByMd5(String context) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(context.getBytes());//update处理
            byte [] encryContext = md.digest();//调用该方法完成计算

            int i;
            StringBuffer buf = new StringBuffer("");
            for (int offset = 0; offset < encryContext.length; offset++) {//做相应的转化（十六进制）
                i = encryContext[offset];
                if (i < 0) i += 256;
                if (i < 16) buf.append("0");
                buf.append(Integer.toHexString(i));
            }
            return buf.toString();
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return  null;
        }
    }

    public static void main(String[] args) {
        String salt = "flyer"+ UUID.randomUUID().toString()+"001";
        String s = MD5Utils.encrypByMd5("flyer@2024" + salt);
        System.out.println(salt);
        System.out.println(s);
    }
}